package com.topfinance.cnaps2.service.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;

import com.topfinance.cnaps2.dto.TblTxDto;
import com.topfinance.cnaps2.dto.XMLMsgDto;
import com.topfinance.cnaps2.ebo.TblTxEbo;
import com.topfinance.cnaps2.service.ITblTxManager;
import com.topfinance.frame.dao.HibernateEntityDao;
import com.topfinance.frame.exception.AppException;
import com.topfinance.frame.util.StringUtil;

/**
 * 该类自动实现了dao的一般方法，如add, remove, update
 * 在service中出现的大部分情况下是在向后台提交数据前的处理(如校验)及获取后台数据后的处理等
 * @author
 *
 */

public class TblTxManagerImpl extends HibernateEntityDao<TblTxEbo> implements ITblTxManager {

	private static final Log log = LogFactory.getLog(TblTxManagerImpl.class);

	public void addTblTx(TblTxEbo o) throws AppException{
    	save(o);
    }
	
	public void editTblTx(TblTxEbo o) throws AppException{
    	saveOrUpdate(o);
    }
	
	//获得传输协议
	public TblTxEbo getTblTx(String uid) throws AppException{
		return (TblTxEbo)get(uid);
	}

	//获得发送接收报文内容
	public List getTblTxXml(String auditid) throws AppException{
		String hql = "select new com.topfinance.cnaps2.dto.XMLMsgDto(t.bin) from TblResendEbo t " ;
		String where = " t.auditId = '" + auditid + "'";
		List<Object> paramList = new ArrayList<Object>();
		if (isNotBlank(where)) {
			where = " where " + where;
		}
		hql = hql + where;
		List list = find(hql,paramList.toArray());
		int size = list.size();
		for(int i=0;i<size;i++){
			try{
			XMLMsgDto x = (XMLMsgDto)list.get(i);
			long length = x.getBlob().length();
			String bin = new String(x.getBlob().getBytes(1, (int)length));
			x.setBlob(null);
			x.setContent(bin);
			list.set(i, x);
			}catch(SQLException sql){
				log.debug("[Error]" + sql.getMessage());
			}
		}
		return list; 		
	}
	
	
	public void deleteTblTx(TblTxEbo o) throws AppException{
		removeById(o.getClass(),o.getAuditId());
    }

	//获得传输协议列表
	public List getAllTblTxList() throws AppException{
		//String hql = "select new com.topfinance.cnaps2.dto.TblTxDto(t.auditId, t.docId, t.txId, t.opName, t.partner, t.host, t.status, t.direction, t.description, t.ts, t.startdate) ";
		String hql = " from TblTxEbo t ";
		String where = "";
		List<Object> paramList = new ArrayList<Object>();
		if (isNotBlank(where)) {
			where = " where " + where;
		}
		hql = hql + where;
		List list = find(hql,paramList.toArray());
		int size = list.size();
		for(int i=0;i<size;i++){
			TblTxEbo tx = (TblTxEbo)list.get(i);
			TblTxDto t = new TblTxDto();
			BeanUtils.copyProperties(tx, t);
			t.setTsEx(StringUtil.convertDate(tx.getTs()));
			t.setStartdateEx(StringUtil.convertDate(tx.getStartdate()));
			list.set(i, t);
		}
		return list;
	}
}
